package com.zeng.jiudian.servlet.product;

import com.alibaba.fastjson.JSONObject;
import com.zeng.jiudian.bean.ProductModel;
import com.zeng.jiudian.service.ProductService;
import com.zeng.jiudian.service.impl.ProductServiceImpl;
import com.zeng.jiudian.utils.Upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author JJ_yo
 * @Date 2020/7/23 - 15:03
 */
@WebServlet("/back/product/add")
public class ProductAddServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        //处理乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        Upload upload = new Upload();
        String result = upload.imgUpload(req);
        String[] results = result.split("@@");

        ProductModel productModel = new ProductModel();
        productModel.setProductName(results[0]);
        productModel.setEnName(results[1]);
        productModel.setMarketPrice((results[2] == null || "".equals(results[2])) ? -1 : Double.parseDouble(results[2]));
        productModel.setPrice((results[3] == null || "".equals(results[3])) ? -1 : Double.parseDouble(results[3]));
        productModel.setContent(results[4]);
        productModel.setIsShow((results[5] == null || "".equals(results[5])) ? -1 : Integer.parseInt(results[5]));
        productModel.setRecommend((results[6] == null || "".equals(results[6])) ? -1 : Integer.parseInt(results[6]));
        productModel.setImg(results[7]);
        productModel.setIntroduction(results[8]);
        productModel.setProductTypeId((results[9] == null || "".equals(results[9])) ? null : Integer.parseInt(results[9]));

        ProductService productService = new ProductServiceImpl();
        int count = productService.add(productModel);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count", count);
        resp.getWriter().println(jsonObject);
    }
}
